import { defineStore } from 'pinia'
import { useItemsStore } from './items'

export const useInventoryStore = defineStore('inventory', {
    state: () => ({
        lowStockThreshold: 3, // 低库存阈值
        expiryWarningDays: 7, // 过期警告天数
        loading: false,
        error: null
    }),

    getters: {
        getLowStockItems: () => {
            const itemsStore = useItemsStore()
            return itemsStore.items.filter(item => item.quantity <= 3)
        },

        getExpiringItems: (state) => {
            const itemsStore = useItemsStore()
            const today = new Date()
            const warningDate = new Date()
            warningDate.setDate(today.getDate() + state.expiryWarningDays)

            return itemsStore.items.filter(item => {
                if (!item.expiryDate) return false
                const expiryDate = new Date(item.expiryDate)
                return expiryDate <= warningDate && expiryDate >= today
            })
        },

        getExpiredItems: () => {
            const itemsStore = useItemsStore()
            const today = new Date()

            return itemsStore.items.filter(item => {
                if (!item.expiryDate) return false
                const expiryDate = new Date(item.expiryDate)
                return expiryDate < today
            })
        },

        getInventoryAlerts: (state) => {
            const lowStock = state.getLowStockItems
            const expiring = state.getExpiringItems
            const expired = state.getExpiredItems

            return {
                lowStock,
                expiring,
                expired,
                totalAlerts: lowStock.length + expiring.length + expired.length
            }
        }
    },

    actions: {
        updateLowStockThreshold(threshold) {
            this.lowStockThreshold = threshold
        },

        updateExpiryWarningDays(days) {
            this.expiryWarningDays = days
        },

        // 清除缓存的方法，用于位置切换等场景
        clearCache() {
            // 重置状态或清除缓存
            this.loading = false
            this.error = null
            // 不需要主动清除物品数据，因为inventory store依赖于items store
        },

        // 更新物品库存数量
        async updateItemQuantity(itemId, newQuantity) {
            const itemsStore = useItemsStore()
            return await itemsStore.updateItem(itemId, { quantity: newQuantity })
        },

        // 更新物品过期日期
        async updateItemExpiryDate(itemId, newExpiryDate) {
            const itemsStore = useItemsStore()
            return await itemsStore.updateItem(itemId, { expiryDate: newExpiryDate })
        }
    }
}) 